<?php
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/models/interfaces/IClient.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/views/GeneralView.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/daos/ClientsDAO.php');
//require_once(realpath(dirname(__FILE__)) . '/../../Aplicación/controlers/interfaces/IController.php');

/**
 * @access public
 * @author Edgar Morán
 * @package Aplicación.controlers
 */
class ClientsController implements IController {
	/**
	 * @AssociationType Aplicación.models.interfaces.IClient
	 * @AssociationKind Composition
	 */
	public $_iClient;
	/**
	 * @AssociationType Aplicación.views.GeneralView
	 * @AssociationKind Composition
	 */
	public $_generalView;
	/**
	 * @AssociationType Aplicación.daos.ClientsDAO
	 * @AssociationKind Composition
	 */
	public $_clientsDAO;
    
    /**
	 * @AttributeType array
	 */
	public $_actionErrors;
    
    
    /**
     * Constructor method for class
     */
    public function __construct(){
        $this->_clientsDAO = new ClientsDAO();
        $this->_generalView = null;
        $this->_iClient = null;
        $this->_actionErrors = null;
    }

	/**
	 * @access public
	 * @return boolean
	 * @ReturnType boolean
	 */
	public function addClient() {
        
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLaddClient);
		$util = new Validations();
		$successMessage= NULL;
		
		$view->tpl->pageTitle="Agregar Cliente";
		$view->tpl->actionTitle="Agregar cliente";
		$view->tpl->actionError=false;

		$params['idTypes']= array(
			array(
		      "value" => '',
		      "name" => 'Seleccione el tipo de Identificación',
		      "selected" => true
		    ),
		    array(
		      "value" => '1',
		      "name" => 'CC',
		      "selected" => false
		    ),
		    array(
		      "value" => '2',
		      "name" => 'CE',
		      "selected" => false
		    ),
		    array(
		      "value" => '3',
		      "name" => 'NIT',
		      "selected" => false
		    ),
		);
        
		//si se va a agregar un cliente
    	if(!empty($params['submit'])){
            
            $aIdType = $params['idType'];
            $aClientId = $params['clientId'];
            $aName = $params['name'];
            $aLastName = $params['lastName'];
            $aAddress = $params['address'];
            $aPhone = $params['phone'];
            $aEmail = $params['email'];
            
            //print_r($params);
            
            if($this->validateClientParams($aIdType, $aClientId, $aName, $aLastName, $aAddress, $aPhone, $aEmail)){
                
                $this->_iClient = new PhoneClient($aIdType, $aClientId, $aName, $aLastName, $aAddress, $aPhone, $aEmail);
                if($this->_clientsDAO->addClient($this->_iClient)){
					setCookieLive ("MensajeExito", str_replace('$', $aName." ".$aLastName, SUCCESSAddClient) , time()+3600);
					//echo "si";
					header('Location:'.ADDCLIENT);
                }
                else{
					$view->tpl->actionError=ERRORDB;
                }
            }
            else {
                //error con los parámetros de entrada
				$seletecValue=$util->array_search_key($params['idType'],$params['idTypes']);
				if(!empty($seletecValue)){
					$params['idTypes'][0]['selected']=false;
					$params['idTypes'][$seletecValue]['selected']=true;
				}
				$view->tpl->actionError=ERRORGeneral;
				$view->tpl->actionErrors=$this->_actionErrors;
                //print_r($this->_actionErrors);
            }
			
		}
		else{
			if(isset($_COOKIE['MensajeExito']))
				$successMessage=$_COOKIE['MensajeExito'];
			removeCookieLive('MensajeExito');
		}
		$view->tpl->params=$params;
		$view->tpl->successMessage=$successMessage;
		//$view->tpl->categoryList =
		$result = $view->render();    
		$fc->setBody($result);
        
	}
    
    /**
     * @param string $aIdType
     * @param int $aClientId
     * @param string $aName
     * @param string $aLastName
     * @param string $aAddress
     * @param string $aPhone
     * @param string $aEmail
     * @return true if correctly validated, false otherwise
     */
    public function validateClientParams($aIdType, $aClientId, $aName, $aLastName, $aAddress, $aPhone, $aEmail){
		$errors=NULL;
		$validState=true;
		$valid = new Validations();
		$valid->validVariable('idType', $aIdType, true , 'enum', 1, 1, NULL, NULL, array(1,2,3));
		$valid->validVariable('clientId', $aClientId, true,'int', 1, 9999999999);
		$valid->validVariable('name', $aName, true, 'string', 2, 200);
		$valid->validVariable('lastName', $aLastName, true, 'string', 2, 200);
		$valid->validVariable('address', $aAddress, true, 'string', 5, 200);
		$valid->validVariable('phone', $aPhone, true, 'string', 7, 10);
		$valid->validVariable('email', $aEmail, true, 'email', 8, 200);
        
		if ($valid->hasError()){
			//print_r($valid->getErrors());
			$errors=$valid->getErrors();
			$validState=false; 
		}
        
        if($validState && $this->_clientsDAO->existUserEmail($aEmail)){
			//echo "si";
			$errors['email']=str_replace('$', $aEmail, ERRORAddClientExistClientEmail) ;
			//$errors['email']=
			$this->_actionErrors=$errors;
			$validState=false;
        }
        
        if($validState && $this->_clientsDAO->existUserId($aIdType, $aClientId)){
			$errors['idType']=str_replace('$', $aClientId, ERRORAddClientExistClientId) ;
			$errors['clientId']=NULL;
			$this->_actionErrors=$errors;
			$validState=false;
        }
        
		$this->_actionErrors=$errors;	
			
		return $validState;
    }

	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function deactivateClient($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_clientsDAO->deactivateUser($aId);
	}

	/**
	 * @access public
	 * @param int aId
	 * @return Aplicación.models.interfaces.IClient
	 * @ParamType aId int
	 * @ReturnType Aplicación.models.interfaces.IClient
	 */
	public function getClient($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		$client = $this->_clientsDAO->getClient($aId);
        if ($client != false){
            $this->_iClient = new PhoneClient($client['idType'], $client['clientId'], $client['name'], $client['lastName'], $client['address'], $client['phone'], $client['email'], $client['access']);
            return $this->_iClient;
        }
        return false;
	}

	/**
	 * @access public
	 * @param int aId
	 * @return void
	 * @ParamType aId int
	 * @ReturnType void
	 */
	public function printClient($aId) {
        //validate id
		//call dao getClient
        //armar objeto y mandar a imprimir
	}

	/**
	 * @access public
	 * @return array
	 * @ReturnType array
	 */
	public function getClients() {
		return $this->_clientsDAO->getClients();
	}

	/**
	 * @access public
	 * @return void
	 * @ReturnType void
	 */
	public function listClients() {
		$fc = FrontController::getInstance();
    	$params = $fc->getParams();// Not yet implemented
		$view = new View(TPLlistClients);
		$view->tpl->hasItems=false;
		
		$view->tpl->pageTitle="Listar Clientes";
		$view->tpl->actionTitle="Listado de Clientes";
		
		if ($this->_clientsDAO->howManyClients()){
			$view->tpl->hasItems=$this->_clientsDAO->howManyClients();
			$clients=$this->getClients();
			$needle=array( array ('key'=>'idType', 'search'=> '1', 'replace'=>'CC'),
							array ('key'=>'idType', 'search'=> '2', 'replace'=>'CE'),
							array ('key'=>'idType', 'search'=> '3', 'replace'=>'NIT') );
            
			$clients=arrayReplace($needle, $clients);
			$view->tpl->clients=$clients;
			
		}
		$result = $view->render();    
		$fc->setBody($result);
	}

	/**
	 * @access public
	 * @param int aId
	 * @return boolean
	 * @ParamType aId int
	 * @ReturnType boolean
	 */
	public function activateClient($aId) {
        $valid = new Validations();
        $valid->validVariable($aId, true,'int', 1, 9999999999);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_clientsDAO->activateUser($aId);
	}

	/**
	 * @access public
	 * @param string aSearchString - it is the identification number of the client
	 * @return array
	 * @ParamType aSearchString string
	 * @ReturnType array
	 */
	public function searchClients($aSearchString) {
        $valid = new Validations();
        $valid->validVariable($aSearchString, true,'string', 1, 100);
		if ($valid->hasError()){
			return false; 
		}
		return $this->_clientsDAO->searchClient($aSearchString);
	}
}
?>